﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

using WorkStation.Frameworks.Core.Data.DataTableValidate.Rules;

namespace WorkStation.Frameworks.Core.Data.DataTableValidate
{
    /// <summary>
    /// * 默认Excel -> DataTable的验证访问
    /// </summary>
    public class DefaultValidateSpecification : IValidateSpecification
    {
        public List<IRule> Rules { get; set; }

        public List<ValidateResult> Validate(DataTable table) 
        {
            List<ValidateResult> res = new List<ValidateResult>();

            if (this.Rules == null) { return res; }

            #region * 是用DataTableFormatRule验证表格式（表格式验证不通过，则后面的规则不再验证）

            TableRuleBase formatRule = this.Rules.SingleOrDefault(v => v.GetType() == typeof(DataTableFormatRule)) as TableRuleBase;

            if (formatRule != null)
            {
                res.Add(formatRule.Execute(table));

                // 如果表格式不符合，直接返回结果，不做后续检查。
                if (!res[0].IsSuccess) 
                {
                    return res;
                }
            }

            #endregion

            #region * 使用基于TableRuleBase的规则从表维度验证

            List<IRule> tableRules = this.Rules.Where(v => v is TableRuleBase && v.GetType() != typeof(DataTableFormatRule)).ToList();

            foreach (TableRuleBase tableRule in tableRules)
            {
                res.Add(tableRule.Execute(table));
            }

            #endregion

            #region * 使用基于RowRuleBase的规则从行维度验证

            int lineIndex = 2;

            foreach (DataRow row in table.Rows) 
            {
                List<IRule> rowRules = this.Rules.Where(v => v is RowRuleBase).ToList();

                foreach (RowRuleBase rowRule in rowRules) 
                {
                    res.Add(rowRule.Execute(row, lineIndex));
                }

                lineIndex++;
            }

            #endregion

            return res;
        }
    }
}
